<template>
  <div class="dream-container">
    <!-- 顶部层级 -->
    <header class="header">
      <div class="developer-info">
        <img :src="developer.photo" alt="开发者照片" class="photo">
        <div>
          <h2>{{ developer.name }}</h2>
          <p>学号: {{ developer.studentId }}</p>
          <p class="motto">座右铭: {{ developer.motto }}</p>
        </div>
      </div>
    </header>

    <!-- 次级导航层 -->
    <nav class="nav">
      <router-link to="/dream">梦想描绘</router-link>
      <router-link to="/tasks">分解设计</router-link>
      <router-link to="/plan">制定计划</router-link>
      <router-link to="/execute">执行计划</router-link>
    </nav>

    <!-- 核心内容层 -->
    <main class="main-content">
      <div class="dream-display">
        <h3>我的梦想</h3>
        <ul>
          <li v-for="(dream, index) in dreams" :key="index">
            {{ dream.dream }}
            <button @click="removeDream(dream.id)">删除</button>
          </li>
        </ul>
      </div>

      <div class="dream-input">
        <textarea v-model="newDream" placeholder="输入你的梦想..."></textarea>
        <button @click="addDream">添加梦想</button>
        <button @click="exportDreams">导出JSON</button>
        <button @click="importDreams">导入JSON</button>
        <input type="file" ref="fileInput" @change="handleFileUpload" accept=".json" style="display: none;">
      </div>
    </main>

    <!-- 底部固定层 -->
    <footer class="footer">
      <p>© 2025 22215120229韬子同学 为梦成真开发者</p>
    </footer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      developer: {
        name: '韬子同学',
        studentId: '22215120229',
        photo: new URL('../assets/developer.jpg', import.meta.url).href,
        motto: 'Perseverance and Determination.'
      },
      dreams: [],
      newDream: ''
    }
  },
  methods: {
    exportDreams() {
      const tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
      const plans = JSON.parse(localStorage.getItem('plans') || '[]')
      const logs = JSON.parse(localStorage.getItem('logs') || '[]')
      
      // 构建嵌套结构
      const nestedDreams = this.dreams.map(dream => {
        const dreamTasks = tasks.filter(task => task.dreamId == dream.id)
          .map(task => {
            const taskPlans = plans.filter(plan => plan.taskId == task.xrwID)
              .map(plan => {
                const planLogs = logs.filter(log => log.planId == plan.id);
                return {
                  ...plan,
                  logs: planLogs
                };
              });
            return {
              ...task,
              plans: taskPlans
            };
          });
        return {
          ...dream,
          tasks: dreamTasks
        };
      });
      
      const exportData = {
        dreams: nestedDreams
      };
      const data = JSON.stringify(exportData, null, 2);
      const blob = new Blob([data], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'dream-plan-' + new Date().toISOString().slice(0, 10) + '.json';
      link.click();
      URL.revokeObjectURL(url);
    },
    importDreams() {
      this.$refs.fileInput.click();
    },
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result);
          if (data.dreams) {
            // 解构嵌套数据
            const flatData = {
              dreams: [],
              tasks: [],
              plans: [],
              logs: []
            };
            
            data.dreams.forEach(dream => {
              flatData.dreams.push({
                dream: dream.dream,
                id: dream.id,
                tasks: []
              });
              
              if (dream.tasks) {
                dream.tasks.forEach(task => {
                  flatData.tasks.push({
                    ...task,
                    dreamId: dream.id
                  });
                  
                  if (task.plans) {
                    task.plans.forEach(plan => {
                      flatData.plans.push({
                        ...plan,
                        taskId: task.xrwID,
                        dreamId: dream.id
                      });
                      
                      if (plan.logs) {
                        plan.logs.forEach(log => {
                          flatData.logs.push({
                            ...log,
                            planId: plan.id
                          });
                        });
                      }
                    });
                  }
                });
              }
            });
            
            this.dreams = flatData.dreams;
            this.saveDreams();
            localStorage.setItem('tasks', JSON.stringify(flatData.tasks));
            localStorage.setItem('plans', JSON.stringify(flatData.plans));
            localStorage.setItem('logs', JSON.stringify(flatData.logs));
          }
          this.$router.go(); // 刷新页面以加载新数据
        } catch (error) {
          console.error('Error parsing JSON:', error);
        }
      };
      reader.readAsText(file);
    },
    addDream() {
      if (this.newDream) {
        const dreamId = Date.now()
        this.dreams.push({
          dream: this.newDream,
          id: dreamId,
          tasks: []
        })
        localStorage.setItem('dreamId', dreamId)
        this.saveDreams()
        this.newDream = ''
      }
    },
    saveDreams() {
      localStorage.setItem('dreams', JSON.stringify(this.dreams))
      localStorage.setItem('dream', this.dreams.length > 0 ? this.dreams[0].dream : '')
    },
    removeDream(id) {
      const index = this.dreams.findIndex(dream => dream.id === id);
      if (index !== -1) {
        this.dreams.splice(index, 1);
        this.saveDreams();
        if (this.dreams.length === 0) {
          localStorage.removeItem('dream');
        }
      }
    }
  },
  mounted() {
    const savedDreams = localStorage.getItem('dreams')
    if (savedDreams) {
      this.dreams = JSON.parse(savedDreams)
    }
  }
}
</script>

<style scoped>
.dream-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
.header {
  background: linear-gradient(135deg, rgb(170, 207, 252), rgb(187, 208, 251), rgb(178, 236, 248));
  padding: 20px;
  display: flex;
  justify-content: center;
}
.developer-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  text-align: center;
}
.photo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}
.motto {
  font-style: italic;
}
.nav {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background: rgba(255, 255, 255, 0.7);
}
.nav a {
  text-decoration: none;
  color: #333;
}
.main-content {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 20px;
}
.dream-display {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, rgb(170, 207, 252), rgb(187, 208, 251), rgb(178, 236, 248));
  border-radius: 5px;
}
.dream-input textarea {
  width: 100%;
  height: 100px;
  padding: 10px;
  margin-bottom: 10px;
}
.footer {
  text-align: center;
  padding: 10px;
  background: linear-gradient(135deg, rgb(170, 207, 252), rgb(187, 208, 251), rgb(178, 236, 248));
}
</style>